import json

def list_output(curr_level, max_index, outfilename):
    f = open(outfilename, 'w')
    str2write = ""
    curr_node = 1
    while curr_node <= max_index:
        str2write += curr_level[curr_node] + "\n"
        curr_node += 1
    f.write(str2write)
    f.close()

def history2list(filename):
    f = open(filename)
    myjson = json.load(f)
    if len(myjson) != 8:
        print("Something Wrong")
        return
    lowest_level = dict()
    max_index = 0
    for small_cluster in myjson[7]:
        for mat_id in small_cluster['clus']:
            lowest_level[mat_id] = small_cluster['id']
            if mat_id > max_index:
                max_index = mat_id
    #print("Max index: " + str(max_index))
    #print("Nodes included: " + str(len(lowest_level)))
    #
    parent = [ dict() ]
    for level in [1, 2, 3, 4, 5, 6, 7]:
        parent.append(dict())
        for acluster in myjson[level]:
            parent[level][acluster['id']] = acluster['prt']
    #
    list_output(lowest_level, max_index, "7")
    #
    curr_level = lowest_level
    for level in [6, 5, 4, 3, 2, 1, 0]:
        curr_node = 1
        while curr_node <= max_index:
            curr_level[curr_node] = parent[level+1][curr_level[curr_node]]
            curr_node += 1
        #
        list_output(curr_level, max_index, str(level))
        #
    print("done.")
    return

